package com.example.service.impl;

import com.example.model.NoticeEvent;
import com.example.service.AsyncService;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;

@Service
public class AsyncServiceImpl implements AsyncService {

    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public String testEventPublish() {
        NoticeEvent noticeEvent = new NoticeEvent("测试事件发布","hello world");
        System.out.println("发布线程："+Thread.currentThread().getName()+"  开始发布数据");
        applicationEventPublisher.publishEvent(noticeEvent);
        return "success";
    }

    @Async("custom-executor")
    @Override
    public Future<String> asyncFuture() {
        String result = "线程："+Thread.currentThread().getName()+" 返回Future";
        return new AsyncResult<>(result);
    }

    @Async("custom-executor")
    @Override
    public CompletableFuture<String> asyncCompletableFuture() {
        String result = "线程："+Thread.currentThread().getName()+" 返回CompletableFuture";
        return CompletableFuture.completedFuture(result);
    }

    @Async("custom-executor")
    @Override
    public ListenableFuture<String> asyncListenableFuture() {
        String result = "线程: "+Thread.currentThread().getName()+" 返回ListenableFuture";
//        int i = 10/0;
        return new AsyncResult<>(result);
    }

    @Async("custom-executor")
    @Override
    public void asyncWithoutResult() {
        System.out.println("线程："+Thread.currentThread().getName()+" 执行无返回值异步");
    }


}
